package com.ovopark.firecar.utils

import android.content.Context
import android.util.Log
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.ovopark.firecar.bean.User
import com.ovopark.firecar.common.Constants
import com.ovopark.firecar.manager.AppDataAttach


/**
 * @author: XieJian
 * Email:   xiejian@ovopark.com
 * Date:    2017/10/26
 * Description: 用户登录控制工具
 */
object LoginUtils {
    private const val TAG = "LoginUtils"
    @JvmStatic
    fun saveCacheUser(user: User?) {
        Log.i(TAG, "saveCacheUser(User user):$user")
        if (user != null) {
            AppDataAttach.attachUser(user)
        }
    }

    @JvmStatic
    fun clearCacheUser() {
        AppDataAttach.clearCacheUser()
    }

    /**
     * 获取缓存的用户数据，如果未获取到，关闭当前界面，且跳转至登录界面
     *
     * @ return
     */
    @JvmStatic
    val cachedUser: User?
        get() = AppDataAttach.getUser()

    //return AppDataAttach.getUserDef(UserConfig.USER_ID);
    @JvmStatic
    val cachedUserId: String
        get() {
            try {
                return cachedUser?.id.toString()
                //return AppDataAttach.getUserDef(UserConfig.USER_ID);
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return ""
        }

    //return AppDataAttach.getUserDef(UserConfig.USER_TOKEN);
    @JvmStatic
    val cachedUserToken: String
        get() {
            Log.i(TAG, "getCachedUserToken()")
            try {
                cachedUser?.token?.let{
                    return it
                }
                //return AppDataAttach.getUserDef(UserConfig.USER_TOKEN);
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return ""
        }

    fun getCacheUserJsonString(context: Context?): String {
        return context?.let {
            SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                ?.getParam(it, Constants.Prefs.CACHE_USER, null)
        } as String
    }

    /**
     * IM登录状态
     */
    @JvmStatic
    fun setImLoginState(context: Context, imState: Boolean) {

//        SharedPreferencesUtils.getInstance(Constants.USER_INFO)
//                .setParam(context, Constants.IM_STATE, imState);
        val settings = context.getSharedPreferences(Constants.USER_INFO, Context.MODE_PRIVATE)
        val editor = settings.edit()
        editor.putBoolean(Constants.IM_STATE, imState)
        editor.apply()
    }

    @JvmStatic
    fun getImLoginState(context: Context): Boolean {
        val sharedata = context.getSharedPreferences(Constants.USER_INFO, Context.MODE_PRIVATE)
        //        SharedPreferences sharedata = BaseApplication.getContext().getSharedPreferences(Constants.USER_INFO, Context.MODE_PRIVATE);
        return sharedata.getBoolean(Constants.IM_STATE, false)
    }

    /**
     * 同userId
     *
     * @param id
     * @return
     */
    @JvmStatic
    fun isSameUserId(id: String?): Boolean {
        val userId = cachedUserId
        return id != null && userId == id
    }

    /**
     * 判断是否有某种权限
     *
     * @param privilegesName 需要判断的权限name
     * @return
     */
    @JvmStatic
    fun isPrivileges(privilegesName: String): Boolean {
        val privileges = AppDataAttach.getPrivileges()
        if (!ListUtils.isEmpty(privileges)) {
            for (obj in privileges) {
                if (privilegesName == obj.privilegeName) {
                    return true
                }
            }
        }
        return false
    }

    /**
     * save base url
     */
    @JvmStatic
    fun saveUrlHistory(context: Context?, urlList: List<String?>?) {
        SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
            ?.setParam(
                context,
                Constants.Prefs.BASE_URL_HISTORY_KEY,
                JSONArray.toJSONString(urlList)
            )
    }

    @JvmStatic
    fun getUrlHistory(context: Context?): List<String>? {
        try {
            val urlList = context?.let {
                SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                    ?.getParam(it, Constants.Prefs.BASE_URL_HISTORY_KEY, "")
            } as String
            if (!StringUtils.isBlank(urlList)) {
                return JSON.parseArray(urlList, String::class.java)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 推送标识
     */
    @JvmStatic
    fun setSPContentForKey(context: Context?, key: String?, content: String?) {
        SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
            ?.setParam(context, key, content)
    }

    @JvmStatic
    fun getSPContentForKey(context: Context?, key: String?): String {
        return context?.let {
            SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                ?.getParam(it, key, "")
        } as String
    }

    @JvmStatic
    fun clearSPContentForKey(context: Context?, key: String?) {
        if (context != null) {
            SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)?.removeParam(context, key)
        }
    }

    /**
     * 保存地图配置
     * @param context
     * @param mapType
     */
    @JvmStatic
    fun saveMapCache(context: Context?, mapType: Int) {
        SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
            ?.setParam(context, Constants.Prefs.MAP_NAME, mapType)
    }

    /**
     * 获取地图本地缓存配置
     * @param context
     * @return
     */
    @JvmStatic
    fun getMapCache(context: Context?): Int {
        return SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
            ?.getParam(context, Constants.Prefs.MAP_NAME, Constants.MAP.AMAP) as Int
    }

    /**
     * 清除权限缓存
     */
    @JvmStatic
    fun clearCachePrivileges() {
        AppDataAttach.clearCachePrivileges()
    }

    /**
     * 登出处理，所有方法的合并
     */
//    @JvmStatic
//    fun loginOut(context: Context?) {
//        //移除底部activity外所有activity
//        BaseAppManager.instance?.clearToBottom()
//        //退出清除配置的启动图
//        SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
//            ?.setParam(context, Constants.Prefs.SPLAH_PATH + cachedUser?.groupId, "")
//        //单独清理groupid为null路径下的
//        SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
//            ?.setParam(context, Constants.Prefs.SPLAH_PATH, "")
//        //清楚用户登录信息
//        clearCacheUser()
//        //清除权限信息
//        clearCachePrivileges()
//        //清除IMToken
//        if (context != null) {
//            SharedPreferencesUtils.getInstance(Constants.Prefs.PREFER_NAME_IM)?.clearSharePrefer(context)
//        }
//        //关闭一些service，放在HomeActivity里操作（在这里操作的话需要写死service路径，防止以后会变动，导致失效）
//        //清除数据库
//        getInstance(context).clearDB()
//        //清除设备管理记录上次选择的门店缓存
//        SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
//            ?.removeParam(context, Constants.Prefs.SELECTED_SHOP_NAME_AND_ID)
//        //清除语音识别设备信息缓存
//        SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
//            ?.setParam(context, Constants.SpeechIdentify.DEVICE_NAME, "")
//        SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
//            ?.setParam(context, Constants.SpeechIdentify.DEVICE_ID, 0)
//    }

    /**
     *  判断是否是超管
     */
    @JvmStatic
    fun isAdmin(mContext:Context): Boolean {
        val manage = SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                ?.getParam(mContext, Constants.Prefs.SUPER_MANAGER_USER, "-1") as String
        return manage != "-1"
    }
}